﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Reflection;

namespace NExt.Handler.Base.Default
{
    public class ExternalFileReponseStreamBuilder: IReponseStreamBuilder
    {
        private readonly string assemblyPath;

        public ExternalFileReponseStreamBuilder(Assembly assembly)
        {
            string assemblyFilePath = string.Empty;
#if DEBUG
            Uri assemblyUri = new Uri(assembly.CodeBase);
            assemblyFilePath = assemblyUri.AbsolutePath;
#else
            assemblyFilePath = assembly.Location;
#endif
            assemblyPath = Path.GetDirectoryName(assemblyFilePath);
        }

        public Stream Build(HttpContext context)
        {
            string filePath = GetFilePath(context);
            if (!File.Exists(filePath))
                return null;

            FileStream fileStream = new FileStream(filePath, FileMode.Open);
            return fileStream;
        }

        private string GetFilePath(HttpContext context)
        {
            Uri uri = context.Request.Url;
            string fileRelativePath = uri.AbsolutePath.Replace("/", Path.DirectorySeparatorChar.ToString());
            string filePath = string.Format("{0}{1}", assemblyPath, fileRelativePath);
            return filePath;
        }
    }
}
